package com.jews.example.demo.infrastructure.config;

import com.google.common.collect.Iterables;
import com.jews.common.constants.CodeEnum;
import com.jews.common.exception.BusinessException;
import com.jews.common.exception.SystemException;
import com.jews.common.exception.ValidationException;
import com.jews.common.model.JsonObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * Controller全局异常处理类
 * @author JewsChen
 * @title: GlobalExceptionAdvice
 * @date 2022/11/30 0:21
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionAdvice {

    @ExceptionHandler(BusinessException.class)
    public JsonObject handleBusinessException(BusinessException e) {
        log.error("业务异常", e);
        return JsonObject.res(e.getMsg(), e.getData());
    }

    @ExceptionHandler(SystemException.class)
    public JsonObject handleSystemException(SystemException e) {
        log.error("系统异常", e);
        return JsonObject.res(CodeEnum.SystemError);
    }

    @ExceptionHandler(Exception.class)
    public JsonObject handleException(Exception e) {
        log.error("系统异常", e);
        return JsonObject.res(CodeEnum.SystemError);
    }

    @ExceptionHandler(ValidationException.class)
    public JsonObject handleValidateException(ValidationException validationException) {
        if (Iterables.size(validationException.getResults()) > 0) {
            return JsonObject.fail(validationException.getResults().get(0).getMessage());
        }
        return JsonObject.fail(CodeEnum.ParamSetIllegal.getName());
    }


}